package com.example.menuvirtualclient.rule;

import java.util.List;

import android.content.Context;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.ISession;
import com.example.menuvirtualclient.data.SessionFactory;
import com.example.menuvirtualclient.repository.TableRepository;


public class TableRule {

	private ISession _session;
	private final TableRepository _repository;
	
	public TableRule(Context context) {
		_session = SessionFactory.GetSession(context);
		_repository = new TableRepository(context);
	}
	
	public Table[] GetAll() throws Exception {
		try {
			_session.Open();
			List<Table> list = _repository.GetAll();
			Table[] tables = list.toArray(new Table[list.size()]);
			return tables;
		} 
		catch (Exception ex) {
			throw ex;
		}
		finally{
			_session.Close();
		}
	}
	
	public Table Get(int id) throws Exception {
		try {
			_session.Open();			
			return _repository.Get(id);
		} 
		catch (Exception ex) {
			throw ex;
		}
		finally{
			_session.Close();
		}
	}
	
	public Table GetByName(String name) throws Exception{
		try {
			_session.Open();
			Table table = _repository.GetByName(name);
			if(table == null) {
				table = new Table();
				table.setId(1);
				table.setName("001");
				table.setStatus(1);
			}
			return table;
		} 
		catch (Exception ex) {
			throw ex;
		}
		finally{
			_session.Close();
		}
	}
	
	public void Insert(Table entity) throws Exception{
		try {
			_session.Open();
			_repository.Insert(entity);
		} 
		catch (Exception ex) {
			throw ex;
		}
		finally{
			_session.Close();
		}
	}
	
	public void Update(Table entity) throws Exception{
		try {
			_session.Open();
			_repository.Update(entity);
		} 
		catch (Exception ex) {
			throw ex;
		}
		finally{
			_session.Close();
		}
	}
	
	public String[] GetNames() throws Exception {
		try {
			_session.Open();
			List<Table> list = _repository.GetAll();
			Table[] tables = list.toArray(new Table[list.size()]);
			String[] tablesName = new String[tables.length];
			int i = 0;
			for(Table table: tables){
//				tablesName[i] = table.getId() + " - " + table.getName() + " - " + GetName(table.getStatus());
				tablesName[i] = table.getId() + " - " + table.getName();
				i++;
			}
			return tablesName;
		} 
		catch (Exception ex) {
			throw ex;
		}
		finally{
			_session.Close();
		}
	}
	
	private String GetName(int status)
	{
		switch(status){
			case 1:
				return "LIBRE";
			case 2:
				return "OCUPADA";
			default:
				return "";
		}
	}
	
}
